package com.lz.comm.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatEditText;

/**
 * Created by you on 2019/5/22.
 * 记住密码控件
 */

public class PasswordEditText extends AppCompatEditText {
    /**
     * 记住密码时, 显示的只是上一次加密后的密码, 输入框内显示的默认内容
     */
    private static final String DEF_PWD = "********";
    /**
     * 是否是默认显示上次加载的密码状态
     */
    private String encryPassword;

    private boolean isEncryPasswordState;

    public PasswordEditText(Context context) {
        super(context);
        init();
    }

    public PasswordEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        addTextChangedListener(new PasswordEditWatcher());
    }

    /**
     * 记住密码
     * @param encryPassword
     */
    public void rememberPassword(String encryPassword) {
        if (TextUtils.isEmpty(encryPassword)) return;
        this.encryPassword = encryPassword;
        this.isEncryPasswordState = true;
        setText(DEF_PWD);
    }

    /**
     * 清除记住的密码
     */
    public void clearRemember() {
        this.encryPassword = null;
        this.isEncryPasswordState = false;
        setText("");
    }

    public String getEncryPassword() {
        return encryPassword;
    }

    private class PasswordEditWatcher implements TextWatcher {
        /**
         * 0无任何操作, 1 删除, 2 新增
         */
        int state = 0;
        /**
         * 记住密码状态时,初次输入时的字符
         */
        int start = 0, end = 0;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            state = 0;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (isEncryPasswordState) {
                isEncryPasswordState = false;
                return;
            }
            if (TextUtils.isEmpty(encryPassword)) return;
            if (before > 0) {//删除操作
                state = 1;
            } else { //新增
                this.start = start;
                this.end = start + count;
                state = 2;
            }
            encryPassword = null;
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (this.state == 1) {
                setText("");
            } else if (this.state == 2) {
                try {
                    CharSequence sub = s.subSequence(start, end);
                    setText(sub);
                    setSelection(sub.length());
                } catch (Exception e) {}
            }
        }
    }

}
